package com.atguigu.dga.ds.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.dga.ds.bean.TDsTaskDefinition;
import com.atguigu.dga.ds.mapper.TDsTaskDefinitionMapper;
import com.atguigu.dga.ds.service.TDsTaskDefinitionService;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhangchen
 * @since 2024-11-25
 */
@Service
@DS("ds")
public class TDsTaskDefinitionServiceImpl extends ServiceImpl<TDsTaskDefinitionMapper, TDsTaskDefinition> implements TDsTaskDefinitionService {

    @Override
    public void extractSqlFromTaskDefineList(List<TDsTaskDefinition> tDsTaskDefinitionList) {
        for (TDsTaskDefinition tDsTaskDefinition : tDsTaskDefinitionList) {
            String taskParams = tDsTaskDefinition.getTaskParams();
            JSONObject taskParamJsonObj = JSON.parseObject(taskParams);
            String rawScript = taskParamJsonObj.getString("rawScript");
            if(rawScript!=null){
                //先找with 如果能找到则使用with ,否则使用insert
                int fromIndex = rawScript.indexOf("with");
                if(fromIndex==-1){
                    fromIndex = rawScript.indexOf("insert");
                }
                if(fromIndex==-1){ //没有with 或者insert 说明没有sql ，直接返回
                    continue;
                }
                //在找; 如果没有分号，取引号的位置
                int toIndex = rawScript.indexOf(";",fromIndex);
                if(toIndex==-1){
                    toIndex = rawScript.indexOf("\"",fromIndex);
                }
                String sql = rawScript.substring(fromIndex, toIndex);
                tDsTaskDefinition.setSql(sql);
            }


        }


    }
}
